import React, {useState} from 'react';
import {FlatList, ListRenderItemInfo} from 'react-native';
import {RootStackNavigation} from '../../navigator';
import {connect, ConnectedProps} from 'react-redux';
import {useDidMount} from '@/utils/index';
import {IFound} from './../../models/found';
import Item from './Item';

const connector = connect();

type ModelState = ConnectedProps<typeof connector>;

interface IProps extends ModelState {
  navigation: RootStackNavigation; //获取跳转路由之类参数
}

const Found: React.FC<IProps> = props => {
  const {dispatch} = props;
  const [list, setList] = useState<IFound[]>([]);
  const [currentId, setCurrentId] = useState('');
  const [refreshing, setRefreshing] = useState(false); // 决定是否展示下拉刷新动画

  useDidMount(() => {
    dispatch({
      type: 'found/fetchList',
      callback: (data: IFound[]) => {
        console.log(data);
        setList(data);
      },
    });
  });
  const onRefresh = () => {
    setRefreshing(true);
    dispatch({
      type: 'found/fetchList',
      callback: (data: IFound[]) => {
        console.log(data);
        setList(data);
        setRefreshing(false);
      },
    });
  };
  const setCurrentIdItem = (id: string) => {
    setCurrentId(id);
    if (id) {
      dispatch({
        type: 'player/pause',
      });
    }
  };
  const keyExtractor = (item: IFound) => item.id;
  const renderItem = ({item}: ListRenderItemInfo<IFound>) => {
    const paused = currentId !== item.id;
    return <Item data={item} paused={paused} setCurrentId={setCurrentIdItem} />;
  };
  return (
    <FlatList
      data={list}
      renderItem={renderItem}
      keyExtractor={keyExtractor}
      extraData={currentId} // 此组件data数据未发现变化不会刷新组件 所以需要传入额外数据使列表组件刷新
      onRefresh={onRefresh} // 下拉刷新事件
      refreshing={refreshing} // 下拉刷新动画是否显示（一般在完成数据请求后置为false）
    />
  );
};

export default connector(Found);
